﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace Plugins.SignalR
{
    public class SignalRHub : Hub
    {
        private  ILogger<SignalRHub> logger { get; set; }

        /// <summary>
        /// 客户连接成功时触发
        /// </summary>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
            var cid = Context.ConnectionId;
            System.Console.WriteLine(cid);

            //根据id获取指定客户端
            var client = Clients.Client(cid);

            //向指定用户发送消息
           await client.SendAsync("Self", cid);

            //向所有用户发送消息
            await Clients.All.SendAsync("AddMsg", $"{cid}：加入了聊天室");
        }
        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(System.Exception exception)
        {
            var cid = Context.ConnectionId;
            //根据id获取指定客户端
            var client = Clients.Client(cid);
            //像所有用户发送消息
            Clients.All.SendAsync("AddMsg", $"{cid}：断开了连接");
            return base.OnDisconnectedAsync(exception);
        }
    }
}